package com.gcxy.springmybatisplustest.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.gcxy.springmybatisplustest.domain.entity.Api;
import lombok.Data;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.Map;

@Component
@Data
public class LoginInterceptor implements HandlerInterceptor {
    private LocalDateTime begin;
    private LocalDateTime end;
    private static final ObjectMapper objectMapper = new ObjectMapper();
    private Api api = new Api();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("方法执行前.....");
        begin = LocalDateTime.now();
        String method = request.getMethod(); // 获取请求方法
        String requestURL = request.getRequestURI(); // 获取请求url
        Map<String, String[]> parameterMap = request.getParameterMap(); // 获取参数

        api.setBegin(begin);
        api.setMethod(method);
        api.setRequestURL(requestURL);
        api.setParameterMap(parameterMap);
//        System.out.print("访问时间："+ begin+" 请求方法为："+method+" 请求路径为："+requestURL+" 请求参数：");
//        parameterMap.forEach(
//                (key,value) -> System.out.print(key+"="+value+";")
//        );
        return true;
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("方法执行结束后......");
        Thread.sleep(2000); // 模拟等待2s
        end = LocalDateTime.now();
        Duration between = Duration.between(begin, end); // 计算两个时间的差异
        api.setEnd(end);
        api.setBetween(between.toSeconds());
//        String json = objectMapper.writeValueAsString(api);
        System.out.println(api);

    }
}
